package com.vancouver.knows.ui.activity.userpost;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pangu.AMApplication;
import com.pangu.service.ActionException;
import com.pangu.task.mark.ATaskMark;
import com.pangu.ui.browser.PullListItemBrowser;
import com.pangu.ui.refresh.ARefreshViewController;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.business.BSharedPrefManager;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.UserPostInfo;
import com.vancouver.knows.business.task.mark.GetUserPostsTaskMark;
import com.vancouver.knows.business.task.mark.RenewUserPostTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteArticleTaskMark;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.util.CircleTransform;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Chris Li on 2016-07-23.
 */
public class UserPostListsView extends PullListItemBrowser<AMApplication>{

    protected Context mContext;
    protected BusinessModule bModule;
    protected LayoutInflater mInflater;
    protected BSharedPrefManager mSharedPrefManager;

    protected int mClickedItemPosition = -1;

    public UserPostListsView(Context context, ARefreshViewController mController) {
        super(context, mController);
        this.mContext = context;
        this.mInflater = LayoutInflater.from(context);
        this.bModule = ((MainApplication) imContext).getBusinessModule();
        this.mSharedPrefManager = (BSharedPrefManager) imContext.getSharedPrefManager();
    }

    @Override
    protected BaseAdapter createAdapter() {
        return new UserPostsAdapter(mContext);
    }

    @Override
    protected void setListViewParameters(ListView listView) {
        super.setListViewParameters(listView);
        listView.setDivider(new ColorDrawable(ContextCompat.getColor(mContext, R.color.common_bg)));
        listView.setDividerHeight((int) getResources().getDimension(R.dimen.divider_height));
    }

    @Override
    protected void handleLoadNewItems(ATaskMark taskMark) {
        bModule.getServiceWrapper().getUserPosts(this, (GetUserPostsTaskMark) taskMark);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        return false;
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
        super.receiveResult(taskMark, exception, trackerResult);
        if (exception != null) {
            // case in which the user's "following" list is private
            if (taskMark instanceof GetUserPostsTaskMark && ((GetUserPostsTaskMark) taskMark).getPage().equals(GetUserPostsTaskMark.PAGE_FOLLOWING) && exception.getExCode() == 1) {
                setCustomErrorStatusText(exception.getExMessage());
            } else {
                Toast.makeText(mContext, exception.getExMessage(), Toast.LENGTH_SHORT).show();
            }
        } else {
            if (taskMark instanceof RenewUserPostTaskMark) {
                Toast.makeText(mContext, R.string.successful_update, Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void removeDraftItem() {
        if (mClickedItemPosition != -1) {
            bModule.getCacheManager().getUserPostHistoryDraftList().remove(mClickedItemPosition);
            notifyDataSetChanged();
        }
    }

    public class UserPostsAdapter extends BaseAdapter {

        private LayoutInflater mLayoutInflater;
        private List<UserPostInfo> mCurrentList = new ArrayList<>();

        public UserPostsAdapter(Context context) {
            this.mLayoutInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            GetUserPostsTaskMark getUserPostsTaskMark = (GetUserPostsTaskMark) getTaskMark();
            String page = getUserPostsTaskMark.getPage();
            if (page .equals(GetUserPostsTaskMark.PAGE_FOLLOWING)) {
                mCurrentList = bModule.getCacheManager().getUserPostFollowingList(getUserPostsTaskMark.getUserId());
                return mCurrentList.size();
            } else if (page.equals(GetUserPostsTaskMark.PAGE_HISTORY) && StringUtil.isEmptyString(getUserPostsTaskMark.getStatus())) {
                mCurrentList = bModule.getCacheManager().getUserPostHistoryPublishList(getUserPostsTaskMark.getUserId());
                return mCurrentList.size();
            } else if (page.equals(GetUserPostsTaskMark.PAGE_HISTORY) && !StringUtil.isEmptyString(getUserPostsTaskMark.getStatus())) {
                mCurrentList = bModule.getCacheManager().getUserPostHistoryDraftList();
                return mCurrentList.size();
            }

            throw new RuntimeException("Invalid page");
        }

        @Override
        public Object getItem(int position) {
            GetUserPostsTaskMark getUserPostsTaskMark = (GetUserPostsTaskMark) getTaskMark();
            String page = getUserPostsTaskMark.getPage();
            if (page.equals(GetUserPostsTaskMark.PAGE_FOLLOWING)) {
                return bModule.getCacheManager().getUserPostFollowingList(getUserPostsTaskMark.getUserId()).get(position);
            } else if (page.equals(GetUserPostsTaskMark.PAGE_HISTORY) && StringUtil.isEmptyString(getUserPostsTaskMark.getStatus())) {
                return bModule.getCacheManager().getUserPostHistoryPublishList(getUserPostsTaskMark.getUserId()).get(position);
            } else if (page.equals(GetUserPostsTaskMark.PAGE_HISTORY) && !StringUtil.isEmptyString(getUserPostsTaskMark.getStatus())) {
                return bModule.getCacheManager().getUserPostHistoryDraftList().get(position);
            }

            throw new RuntimeException("Invalid page");
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (position == getCount() - 1) {
                tryQueryNewItems(true, ATaskMark.TYPE_DEFAULT);
            }
            ViewHolder viewHolder = null;
            GetUserPostsTaskMark getUserPostsTaskMark = (GetUserPostsTaskMark) getTaskMark();
            String page = getUserPostsTaskMark.getPage();
            if (convertView == null) {
                if (page.equals(GetUserPostsTaskMark.PAGE_HISTORY)) {
                    convertView = mLayoutInflater.inflate(R.layout.uploaded_post_view_item, parent, false);
                    viewHolder = new ViewHolder(convertView);
                } else if (page.equals(GetUserPostsTaskMark.PAGE_FOLLOWING)) {
                    convertView = mLayoutInflater.inflate(R.layout.uploaded_post_view_user_item, parent, false);
                    viewHolder = new ViewHolder(convertView);
                }

                if (convertView != null) {
                    convertView.setTag(viewHolder);
                }

            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            final UserPostInfo userPostInfo = (UserPostInfo) getItem(position);
            if (page.equals(GetUserPostsTaskMark.PAGE_HISTORY)) {
                if (userPostInfo.getPostImages().size() > 0) {
                    Picasso.with(getContext()).load(userPostInfo.getPostImages().get(0)).fit().into(viewHolder.thumbnail);
                } else {
                    viewHolder.thumbnail.setImageResource(0);
                }

                viewHolder.title.setText(userPostInfo.getPostContentSummary());
                viewHolder.date.setText(AppUtils.getEventPdg(userPostInfo.getPdg()));
                viewHolder.statistics.setText(getContext().getString(R.string.post_statistics, userPostInfo.getViewCount(), userPostInfo.getFollowCount()));

                if (userPostInfo.getStatus() != null) {
                    if (userPostInfo.getStatus().equals(UserPostInfo.DRAFT_STATUS)) {
                        viewHolder.status.setTextColor(ContextCompat.getColor(getContext(), R.color.post_green));
                        viewHolder.status.setText(R.string.post_draft);
                        viewHolder.repost.setVisibility(GONE);
                    } else if (userPostInfo.getStatus().equals(UserPostInfo.PUBLISH_STATUS)) {
                        viewHolder.status.setTextColor(ContextCompat.getColor(getContext(), R.color.post_green));
                        viewHolder.status.setText(R.string.post_live);
                        viewHolder.repost.setVisibility(GONE);
                    } else if (userPostInfo.getStatus().equals(UserPostInfo.EXPIRED_STATUS)) {
                        viewHolder.status.setTextColor(ContextCompat.getColor(getContext(), R.color.post_red));
                        viewHolder.status.setText(R.string.post_expired);
                        viewHolder.repost.setVisibility(VISIBLE);
                        viewHolder.repost.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                RenewUserPostTaskMark taskMark = bModule.getTaskMarkPool().getRenewUserPostTaskMark(userPostInfo.getId());
                                bModule.getServiceWrapper().renewUserPost(UserPostListsView.this, taskMark, userPostInfo.getId(), mSharedPrefManager.getUserId());
                                userPostInfo.setStatus(UserPostInfo.PUBLISH_STATUS);
                                notifyDataSetChanged();
                            }
                        });
                    }
                }

                if (!getUserPostsTaskMark.getUserId().equals(mSharedPrefManager.getUserId())) {
                    if (viewHolder.edit != null && viewHolder.delete != null) {
                        viewHolder.edit.setVisibility(GONE);
                        viewHolder.delete.setVisibility(GONE);
                        viewHolder.divider.setVisibility(GONE);
                    }
                } else {
                    if (viewHolder.edit != null && viewHolder.delete != null) {
                        viewHolder.edit.setVisibility(VISIBLE);
                        viewHolder.edit.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mClickedItemPosition = position;
                                Intent intent = new Intent(mContext, CreateUserPostActivity.class);
                                intent.putExtra(CreateUserPostActivity.EDIT_MODE_EXTRA, true);
                                intent.putExtra(CreateUserPostActivity.STATUS_EXTRA, userPostInfo.getStatus());
                                intent.putExtra(CreateUserPostActivity.POST_ID_EXTRA, userPostInfo.getId());
                                ((UserPostListsActivity) mContext).startActivityForResult(intent, CreateUserPostActivity.CREATE_POST_SUCCESS_REQUEST);
                            }
                        });
                        viewHolder.delete.setVisibility(VISIBLE);
                        viewHolder.delete.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showDeleteDialog(userPostInfo.getId(), position);
                            }
                        });
                        viewHolder.divider.setVisibility(VISIBLE);
                    }
                }

                if (convertView != null) {
                    convertView.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(mContext, UserPostDetailActivity.class);
                            intent.putExtra(UserPostDetailActivity.POST_ID_EXTRA, userPostInfo.getId());
                            mContext.startActivity(intent);
                        }
                    });
                }

            } else if (page.equals(GetUserPostsTaskMark.PAGE_FOLLOWING)) {
                if (userPostInfo.getPostImages().size() > 0) {
                    Picasso.with(getContext()).load(userPostInfo.getPostImages().get(0)).fit().into(viewHolder.thumbnail);
                }
                viewHolder.title.setText(userPostInfo.getPostContentSummary());
                viewHolder.date.setText(AppUtils.getEventPdg(userPostInfo.getPdg()));
                viewHolder.statistics.setText(getContext().getString(R.string.post_statistics, userPostInfo.getViewCount(), userPostInfo.getFollowCount()));
                if (!StringUtil.isEmptyString(userPostInfo.getAuthorAvatar())) {
                    Picasso.with(getContext()).load(userPostInfo.getAuthorAvatar())
                            .error(R.drawable.me_icon_login)
                            .placeholder(R.drawable.me_icon_login)
                            .transform(new CircleTransform()).fit().into(viewHolder.avatar);
                } else {
                    Picasso.with(getContext()).load(R.drawable.me_icon_login).fit().into(viewHolder.avatar);
                }
                viewHolder.username.setText(userPostInfo.getPostAuthor());

                if (userPostInfo.getStatus() != null) {
                    if (userPostInfo.getStatus().equals(UserPostInfo.PUBLISH_STATUS)) {
                        viewHolder.status.setTextColor(ContextCompat.getColor(getContext(), R.color.post_green));
                        viewHolder.status.setText(R.string.post_live);
                        if (convertView != null) {
                            convertView.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(mContext, UserPostDetailActivity.class);
                                    intent.putExtra(UserPostDetailActivity.POST_ID_EXTRA, userPostInfo.getId());
                                    intent.putExtra(UserPostDetailActivity.PREVENT_NESTED_NAVIGATION_EXTRA, true);
                                    mContext.startActivity(intent);
                                }
                            });
                        }
                    }
                }

                if (viewHolder.userContainer != null) {
                    viewHolder.userContainer.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(mContext, ProfileActivity.class);
                            intent.putExtra(ProfileActivity.USER_ID_EXTRA, userPostInfo.getAuthorId());
                            mContext.startActivity(intent);
                        }
                    });
                }
            }

            return convertView;
        }

        public class ViewHolder {

            @Bind(R.id.post_thumbnail)
            ImageView thumbnail;
            @Bind(R.id.post_title)
            TextView title;
            @Bind(R.id.post_statistics)
            TextView statistics;
            @Bind(R.id.post_status)
            TextView status;
            @Bind(R.id.post_date)
            TextView date;
            @Bind(R.id.divider)
            View divider;
            @Nullable @Bind(R.id.edit)
            TextView edit;
            @Nullable @Bind(R.id.delete)
            TextView delete;
            @Nullable @Bind(R.id.repost)
            TextView repost;
            @Nullable @Bind(R.id.user_container)
            RelativeLayout userContainer;
            @Nullable @Bind(R.id.user_avatar)
            ImageView avatar;
            @Nullable @Bind(R.id.user_name)
            TextView username;

            public ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }

        private void showDeleteDialog(final String postId, final int position) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.AlertDialogTheme);
            builder.setTitle(R.string.alert_delete_title);
            builder.setMessage(R.string.alert_delete_message);
            builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    UserDeleteArticleTaskMark userDeleteArticleTaskMark = bModule.getTaskMarkPool()
                            .createUserDeleteArticleTaskMark(postId);
                    bModule.getServiceWrapper().userDeleteArticle(UserPostListsView.this, userDeleteArticleTaskMark, postId, mSharedPrefManager.getUserId());
                    mCurrentList.remove(position);
                    notifyDataSetChanged();
                }
            });
            builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }
}
